package edu.nyp.locationservicesapp.utils;

import android.os.Environment;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;

import edu.nyp.locationservicesapp.constant.CustomConstant;

/**
 * 全局异常处理类
 * User:Gaolei  gurecn@gmail.com
 * Date:2017/12/6
 * I'm glad to share my knowledge with you all.
 */
public class CrashHandler implements UncaughtExceptionHandler {
	private static CrashHandler instance;
	
	public static CrashHandler getInstance() {
		if (instance == null) {
			instance = new CrashHandler();
		}
		return instance;
	}

	public void init() {
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread arg0, Throwable arg1) {
		if (Environment.getExternalStorageDirectory() != null) {
			File file = new File(CustomConstant.BASE_PATH);
			boolean mkSuccess;
			if (!file.isDirectory()) {
				mkSuccess = file.mkdirs();
				if (!mkSuccess) {
					mkSuccess = file.mkdirs();
				}
			}
			try {
				FileWriter fw = new FileWriter(CustomConstant.BASE_PATH + "log.txt", true);
				fw.write(new Date() + "\n");
				StackTraceElement[] stackTrace = arg1.getStackTrace();
				fw.write(arg1.getMessage() + "\n");
				for (StackTraceElement aStackTrace : stackTrace) {
					fw.write("file:" + aStackTrace.getFileName() + " class:" + aStackTrace.getClassName()
							+ " method:" + aStackTrace.getMethodName() + " line:" + aStackTrace.getLineNumber() + "\n");
				}
				fw.write("\n");
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		arg1.printStackTrace();
		System.exit(0);
	}
}
